// pages/index/login/regMini/regMini.js
const app = getApp()
const regex = require('../../../../utils/regex')
const request = require('../../../../utils/request')

Page({
  data: {
    phone: '',
    getCode: true,
    countdownTime: 60,
    btnText: '获取验证码',
    radioItems: [
      {name: 0, value: '车主', checked: 'true'},
      {name: 1, value: '员工'}
    ],
    isStaff: 0,
    currentTab: '0',
    businessImg: '',
    cardImg: '',
    repairImg: '',
    mapCtx: '',
    latitude: '',
    longitude: '',
    invite: '',
    imgHost: app.d.imgPath,
    auth_show: false,
    nickname: '',
    placeholderVal: '',
    placeholderVal2: '',
    code: ''
  },

  onLoad(options) {
    if (options.inviteCode) {
      this.setData({
        invite: options.inviteCode
      })
    }
    this.checkAuth()
    this.onLogin()

  },

  onLogin() {
    var self = this
    wx.login({
      success: function (res) {
        if (res.code) {
          self.setData({
            code: res.code
          })
          console.log(res.code)
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      } 
    });
  },


  checkAuth() {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              this.setData({
                nickname: res.userInfo.nickName
              })
            }
          })
        } else {
          this.setData({
            auth_show: true
          })
        }
      }
    })
  },

  onGetUserInfo(e) {
    if (e.detail.userInfo) {
      this.setData({
        auth_show: false
      })
      this.checkAuth()
    } else {
      wx.showModal({
        title: '警告',
        content: '您拒绝了授权，此操作将影响您注册注册，若想正常使用此功能，请返回授权',
        showCancel: false,
        confirmText: '返回授权',
      })
    }
  },
  
  onInviteInput(e) {
    this.setData({
      invite: e.detail.value
    })
  },

  getLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: res => {
        this.setData({
          longitude: res.longitude,
          latitude: res.latitude
        })
      },
      fail: error => {
        wx.showModal({
          title: '温馨提示',
          content: '您拒绝了获取位置授权，此操作将影响您注册修理厂，若想正常使用此功能，请返回授权',
          showCancel: false,
          confirmText: '返回授权',
          success: res => {
            if (res.confirm) {
              wx.openSetting({
                success: res => {
                  if (res.authSetting['scope.userLocation']) {
                    this.getLocation()
                  }
                }
              })
            }
          }
        })
      }
    })
  },
  
  changeTab(e) {
    const current = e.currentTarget.dataset.current
    this.setData({
      currentTab: current
    })
    
    if (current === '1') {
      this.getLocation()
    }
  },

  // 跳转登录页
  toLogin() {
    wx.navigateTo({
      url: '../login'
    })
  },

  // 监听手机号码
  bindPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  radioChange(e) {
    this.setData({
      isStaff:  e.detail.value
    })
  },

  // 获取验证码
  getVerifyCode(event) {
    const phone = this.data.phone
    if (!phone) {
      wx.showToast({
        icon: 'none',
        title: '请输入手机号 '
      })
      return
    }

    if (!regex.phone.test(phone)) {
      wx.showToast({
        icon: 'none',
        title: '手机号格式错误'
      })
      return
    }

    wx.showLoading()
    request.get('send_sms', { phone })
      .then(res => {
        wx.hideLoading()
        this.setData({
          getCode: false
        })
    
        let time = event.target.dataset.time
        const t = setInterval(() => {
          time--
          this.setData({
            countdownTime: time
          })
    
          if (time <= 0) {
            clearInterval(t)
            this.setData({
              countdownTime: 60,
              getCode: true,
              btnText: '重新获取'
            })
    
          }
        }, 1000)

        wx.showToast({
          icon: 'none',
          title: res.msg
        })
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg 
        })
      })
      .finally(_ => {
        
      })
  },

  uploadImg(cb) {
    wx.chooseImage({
      count: 1,
      success: file => {
        wx.showLoading({
          title: '正在上传'
        })
        const tempFilePaths = file.tempFilePaths
        wx.uploadFile({
          url: app.d.severUrl + 'imgUpload',
          filePath: tempFilePaths[0],
          name: 'imgData',
          success: res => {
            cb && cb(JSON.parse(res.data))
            wx.hideLoading()
          },
          fail: error => {
            wx.showToast({
              icon: 'none',
              title: error.msg
            })
          }
        })
      }
    })
  },

  uploadRepairImg() {
    this.uploadImg(res => {
      this.setData({
        repairImg: res.data.image
      })
    })
  },

  uploadCardImg() {
    this.uploadImg(res => {
      this.setData({
        cardImg: res.data.image
      })
    })
  },

  uploadBusinessImg() {
    this.uploadImg(res => {
      this.setData({
        businessImg: res.data.image
      })
    })
  },

  previewImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url,
      urls: [e.currentTarget.dataset.url]
    })
  },

  // form 提交
  formSubmit(e) {
    const value = e.detail.value
    if (!value.phone) {
      wx.showToast({
        icon: 'none',
        title: '请输入手机号'
      })
      return
    }

    if (!regex.phone.test(value.phone)) {
      wx.showToast({
        icon: 'none',
        title: '手机号格式错误'
      })
      return
    }

    if (!value.yzm) {
      wx.showToast({
        icon: 'none',
        title: '请输入验证码'
      })
      return
    }

    if (!value.password) {
      wx.showToast({
        icon: 'none',
        title: '请输入密码'
      })
      return
    }

    if (value.password.length < 6) {
      wx.showToast({
        icon: 'none',
        title: '密码长度不能小于6位'
      })
      return
    }

    if (!value.cpassword) {
      wx.showToast({
        icon: 'none',
        title: '请确认密码'
      })
      return
    }

    if (value.password !== value.cpassword) {
      wx.showToast({
        icon: 'none',
        title: '两次密码填写不一致'
      })
      return
    }   

    if ((+this.data.isStaff === 1) && !this.data.invite) {
      wx.showToast({
        icon: 'none',
        title: '请输入上级邀请码'
      })
      return
    }

    wx.showLoading()

    const data = {
      phone: value.phone,
      password: value.password,
      invite: this.data.invite,
      yzm: value.yzm,
      is_yg: this.data.isStaff,
      wechatname: this.data.nickname,
      code: this.data.code
    }

    request.post('register', data)
      .then(res => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: res.msg
        })

        this.setData({
          placeholderVal: ''
        })

        setTimeout(_ => {
          wx.navigateTo({
            url: '../../login/login',
          })
        }, 1500)
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },

  repairSubmit(e) {
    const value = e.detail.value
    if (!value.repair_name) {
      wx.showToast({
        icon: 'none',
        title: '请填写修理厂名称'
      })
      return
    }

    if (!value.repair_address) {
      wx.showToast({
        icon: 'none',
        title: '请填写修理厂地址'
      })
      return
    }
    
    if (!this.data.repairImg) {
      wx.showToast({
        icon: 'none',
        title: '请添加修理厂照片'
      })
      return
    }

    if (!value.username) {
      wx.showToast({
        icon: 'none',
        title: '请填写用户名'
      })
      return
    }

    if (!value.realname) {
      wx.showToast({
        icon: 'none',
        title: '请填写真是姓名'
      })
      return
    }

    if (!value.phone) {
      wx.showToast({
        icon: 'none',
        title: '请填写联系电话'
      })
      return
    }

    if (!regex.phone.test(value.phone)) {
      wx.showToast({
        icon: 'none',
        title: '无效的手机号码'
      })
      return
    }

    if (!this.data.cardImg) {
      wx.showToast({
        icon: 'none',
        title: '请添加身份证照片'
      })
      return
    }

    if (!this.data.businessImg) {
      wx.showToast({
        icon: 'none',
        title: '请添加营业执照照片'
      })
      return
    }

    if (!value.password) {
      wx.showToast({
        icon: 'none',
        title: '请填写密码'
      })
      return
    }

    if (!value.cpassword) {
      wx.showToast({
        icon: 'none',
        title: '请填写确认密码'
      })
      return
    }


    if (value.password !== value.cpassword) {
      wx.showToast({
        icon: 'none',
        title: '两次密码填写不一致'
      })
      return
    }

    if (!this.data.longitude || !this.data.latitude) {
      wx.showToast({
        icon: 'none',
        title: '未获取到经纬度'
      })
      return
    }

    wx.showLoading()

    const data = {
      username: value.username,
      password: value.password,
      repassword: value.cpassword,
      repair_name: value.repair_name,
      image: this.data.repairImg,
      card_img: this.data.cardImg,
      business_img: this.data.businessImg,
      address: value.repair_address,
      phone: value.phone,
      realname: value.realname,
      x: this.data.longitude,
      y: this.data.latitude,
      code: this.data.code
    }

    request.post('repair_reg', data)
      .then(res => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: res.msg
        })

        this.setData({
          placeholderVal2: '',
          cardImg: '',
          businessImg: '',
          repairImg: '',
        })
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },
})